package cn.wildfire.chat.app.extendsion.classes;

import android.os.Parcel;
import android.os.Parcelable;

import androidx.annotation.NonNull;

import java.security.InvalidKeyException;

/**
 * Create by HEKE, 2019/9/11 10:03
 * TODO 点指示器对象
 */
public class Pointer implements Parcelable {

    public float x;
    public float y;

    public Pointer() {
        super();
    }

    public Pointer(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public Pointer(@NonNull String value) throws InvalidKeyException {
        if(!value.contains(",")){
           throw new InvalidKeyException("Invalid string format!");
        }
        String[] array = value.split("[,]");
        this.x = Float.parseFloat(array[0]);
        this.y = Float.parseFloat(array[1]);
    }

    protected Pointer(Parcel in) {
        x = in.readFloat();
        y = in.readFloat();
    }

    public int dist(Pointer target) {
        if (target == null) {
            return 0;
        }
        float absX = Math.abs(x - target.x);
        float absY = Math.abs(y - target.y);
        return (int) Math.sqrt(absX * absX + absY * absY);
    }

    /**
     * 计算点之间的偏距
     * @param tag 只允许为x或者y
     * @param target
     * @return
     * */
    public float offset(@NonNull String tag,@NonNull Pointer target){
        tag = tag.toLowerCase();
        if(tag.equals("x")){
            return Math.abs(x-target.x);
        }else if(tag.equals("y")){
            return Math.abs(y-target.y);
        }
        return 0;
    }

    public Pointer copy() {
        return new Pointer(x, y);
    }

    public void multitap(Pointer set) {
        if (set == null) {
            return;
        }
        x = set.x;
        y = set.y;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeFloat(x);
        dest.writeFloat(y);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<Pointer> CREATOR = new Creator<Pointer>() {
        @Override
        public Pointer createFromParcel(Parcel in) {
            return new Pointer(in);
        }

        @Override
        public Pointer[] newArray(int size) {
            return new Pointer[size];
        }
    };

    @NonNull
    @Override
    public String toString() {
        return x + "," + y;
    }

}
